import React, { useState, useRef } from 'react'
import { Modal, Input, Button } from 'antd';
import styles from '../../styles/common/alterPassword.scss'
import { IconFont, axiosConfig, backIP, success, error } from './config';
import axios from 'axios'
import { getToken } from './util';

export default function AlterPassword({ visiable, setVisiable }) {
    const [loading, setLoading] = useState(false)
    const [password, setPassword] = useState('')
    const [verifyPassword, setVerifyPassword] = useState('')
    const infoShow = useRef();

    // 清空所有输入框
    const clear = () => {
        setPassword('')
        setVerifyPassword('')
    }
    const handleCancel = () => {
        setVisiable(false)
        clear()
    };
    const handleOk = async () => {
        if (password !== verifyPassword) {
            (infoShow.current as any).innerHTML = '两次密码输入必须一致'
            return
        }
        (infoShow.current as any).innerHTML = ''
        setLoading(true)

        const token: string = getToken();
        const { data: res }: { data: axiosConfig } = await axios.post(`${backIP}/password`, {
            password
        }, {
            headers: {
                Authorization: token
            }
        })
        if (res.code === 0) {
            success(res.message)
            setVisiable(false)
            clear();
        } else {
            error(res.message)
        }
        setLoading(false)
    };
    const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>, type: string) => {
        const constrast = {
            password: setPassword,
            verifyPassword: setVerifyPassword
        }
        if (event && event.target) {
            const value = event.target.value;
            constrast[type](value)
        }
    }

    return (
        <Modal
            title="修改密码"
            visible={visiable}
            onOk={handleOk}
            onCancel={handleCancel}
            footer={[
                <Button key="back" onClick={handleCancel}>
                    Return
                  </Button>,
                <Button key="submit" type="primary" loading={loading} onClick={handleOk}>
                    Submit
                  </Button>,
            ]}
        >
            <Input.Password
                placeholder="密码"
                prefix={<IconFont type='iconmima' className={styles.prefix} />}
                className={styles.input}
                value={password}
                onChange={(e) => { handleInputChange(e, 'password') }}
            />
            <Input.Password
                placeholder="确认密码"
                prefix={<IconFont type='iconmima' className={styles.prefix} />}
                className={styles.input}
                value={verifyPassword}
                onChange={(e) => { handleInputChange(e, 'verifyPassword') }}
            />
            <div ref={infoShow} className={styles.infoShow}></div>
        </Modal>
    )
}
